<script setup>
    import { ref } from 'vue'
    import getTime from '@/utils/moment'
    import { notAddNoticeService, notEditNoticeService } from '@/api/notice'

    // 抽屉的状态
    const drawerState = ref(false)

    // 操作抽屉的状态
    const changeDrawerState = () => {
        drawerState.value = !drawerState.value
    }

    // 接收父传子的数据
    const props = defineProps({
        propsData: Object
    })

    const form = ref()

    // 表单数据
    const drawerFrom = ref({
        title: '',
        content: ''
    })
    // 表单验证
    const rules = ref({
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
    })

    // 打开抽屉
    const open = () => {
        drawerFrom.value = props.propsData.row
    }

    const emits = defineEmits(['add-notice'])
    
    // 发布按钮
    const releaseBtn = async() => {
       await form.value.validate
       drawerFrom.value.date = getTime()
    //  1. 新增公告
       if (props.propsData.status === 'add') {
            const { data } = await notAddNoticeService(drawerFrom.value)
            if (data.status === 0) {
                ElMessage.success(data.message)
                emits('add-notice')
            } else {
                ElMessage.error(data.message)
            }
    // 2. 修改公告
       } else if (props.propsData.status === 'edit') {
        const { data } = await notEditNoticeService(drawerFrom.value)
        if (data.status === 0) {
            ElMessage.success(data.message)
        } else {
            ElMessage.error(data.message)
        }
       } else {

       }
       changeDrawerState()
    }

    // 取消按钮
    const cancellation = () => {
        drawerFrom.value = {}
        changeDrawerState()
    }

     // 向父组件暴露方法
     defineExpose({
        changeDrawerState
    })
</script>

<template>
    <div class="notice-drawer">
        <el-drawer v-model="drawerState" :title="props.propsData.title" size="40%" @open="open" @close="close">
        <span>
            <el-form :model="drawerFrom" :rules="rules" ref="form">
                <el-form-item label="公告标题" prop="title">
                    <el-input placeholder="请输入公告标题" v-model="drawerFrom.title"></el-input>
                </el-form-item>
                <el-form-item label="公告内容" prop="content">
                    <el-input type="textarea" placeholder="请输入公告内容" v-model="drawerFrom.content"></el-input>
                </el-form-item>
                <el-form-item>
                    <div style="margin-left: 70px;">
                        <el-button type="info" @click="cancellation">取消</el-button>
                        <el-button type="primary" @click="releaseBtn" :disabled="props.propsData.status === 'view'">发布</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </span>
    </el-drawer>
    </div>
</template>

<style scoped lang="scss">

</style>